package com.duing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duing.dto.BookQueryDTO;
import com.duing.entity.Book;
import com.duing.enums.ErrorCode;
import com.duing.exception.BusinessException;
import com.duing.mapper.BookMapper;
import com.duing.service.BookService;
import org.springframework.stereotype.Service;



@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    public void validateBook(Book book){
        if(existsByName(book.getName())){
            throw new BusinessException(ErrorCode.DATA_EXISTS.getCode(), "该书已存在");
        }
    }

    public boolean existsByName(String name){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return baseMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public Page<Book> getBooksByKeyword(int page, int size, BookQueryDTO dto) {

        if(page <= 0 || size <= 0){
            throw new BusinessException(ErrorCode.PARAM_ERROR.getCode(), "分页参数错误");
        }

        Page<Book> pageParam = new Page<>(page, size);
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();

        if(dto.getName() != null && !dto.getName().isEmpty()){
            queryWrapper.like("name", dto.getName());
        }
        if(dto.getAuthor() != null && !dto.getAuthor().isEmpty()){
            queryWrapper.like("author", dto.getAuthor());
        }
        if(dto.getAuthor_id() != null){
            queryWrapper.eq("author_id", dto.getAuthor_id());
        }
        if(dto.getType() != null && !dto.getType().isEmpty()){
            queryWrapper.eq("type", dto.getType());
        }
        if(dto.getDescription() != null && !dto.getDescription().isEmpty()){
            queryWrapper.like("description", dto.getDescription());
        }
        if(dto.getStatus() != null){
            queryWrapper.eq("status", dto.getStatus());
        }

        return (Page<Book>) baseMapper.selectPage(pageParam, queryWrapper);
    }
}
